package com.wei.lawyer.ui.activity;

import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.FieldBean;
import com.wei.lawyer.model.WebDataBean;
import com.wei.lawyer.net.presenter.FindPresenter;
import com.wei.lawyer.ui.adapter.BaseDelegateAdapter;
import com.wei.lawyer.ui.adapter.BaseViewHolder;
import com.wei.lawyer.utils.RxUtils;
import com.wei.lawyer.utils.StringUtils;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

/**
 * 作者：赵若位
 * 时间：2018/11/14 13:52
 * 邮箱：1070138445@qq.com
 * 功能：电话咨询
 */
public class PhoneConsultingActivity extends BaseActivity<FindPresenter>
{
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private EditText mPhone;//电话沟通的联系方式

    private DelegateAdapter mAdapter;

    private BaseDelegateAdapter mProcessAdapter, mTypeAdapter, mPayAdapter;


    @Override
    protected int getLayoutResource()
    {
        return R.layout.activity_phone_consulting;
    }

    @Override
    protected void setStatusBarColor()
    {

    }

    @Override
    protected FindPresenter createPresenter()
    {
        return new FindPresenter(this, this);
    }

    @Override
    protected void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        setLeftBack();
        setTitle(getString(R.string.tv_home_phone));

        VirtualLayoutManager manager = new VirtualLayoutManager(mActivity);
        manager.setInitialPrefetchItemCount(3);
        mRecyclerView.setLayoutManager(manager);
        //关闭动效提升效率
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.setItemViewCacheSize(3);

        mAdapter = new DelegateAdapter(manager);
        mRecyclerView.setAdapter(mAdapter);

        initAdapter();
    }


    private void initAdapter()
    {
        //流程
        mProcessAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_phone_consulting_process)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                holder.setText(getString(R.string.tv_do_have_what_question), R.id.tv_title);
            }
        };
        mAdapter.addAdapter(mProcessAdapter);
        mProcessAdapter.setData("");

        //选择方式
        mTypeAdapter = new BaseDelegateAdapter<FieldBean>(this, R.layout.item_quick_consulting_field)
        {

            @Override
            public void convert(BaseViewHolder holder, final int position, FieldBean data)
            {
                holder.setText(data.getName(), R.id.item_title)
                        .setTextColor(getResources().getColor(lastPosition == position ? R.color.white : R.color.textUnSelected), R.id.item_title)
                        .setBackgroundResource(lastPosition == position ? R.drawable.shape_quick_consulting_selected : R.drawable.shape_quick_consulting_unselected, R.id.item_title)
                        .itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (lastPosition == position) return;
                        //TODO 选择类型
                        lastPosition = position;
                        notifyDataSetChanged();
                    }
                });
            }

            @Override
            public LayoutHelper onCreateLayoutHelper()
            {
                GridLayoutHelper helper = new GridLayoutHelper(4);
                helper.setBgColor(getResources().getColor(R.color.white));
                helper.setAutoExpand(false);
                helper.setPaddingLeft(getResources().getDimensionPixelOffset(R.dimen.dp_14));
                helper.setPaddingRight(getResources().getDimensionPixelOffset(R.dimen.dp_14));
                return helper;
            }

            @Override
            protected int setLastPosition()
            {
                return 0;
            }
        };
        mAdapter.addAdapter(mTypeAdapter);

        mPayAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_phone_consulting_pay_type)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                //设置收费标准
                StringBuilder builder = new StringBuilder();
                builder.append(getString(R.string.tv_money))
                        .append(App.mConfig != null ? App.mConfig.getCallBroadcastPrice() / 100 : 0)
                        .append("/")
                        .append(App.mConfig != null ? App.mConfig.getCallBroadcastMinutes() : 0)
                        .append("分钟");
                holder.setText(builder.toString(), R.id.tv_price);
                setUrgentUi((TextView) holder.getView(R.id.tv_pay_urgent_descript_1));
                setContactUi((TextView) holder.getView(R.id.tv_contact));
                //初始化联系方式
                mPhone = holder.getView(R.id.et_phone);
            }

            //异步设置平台加急UI样式
            private void setUrgentUi(final TextView view)
            {
                if (view != null)
                {
                    Observable.create(new ObservableOnSubscribe<SpannableString>()
                    {
                        @Override
                        public void subscribe(ObservableEmitter<SpannableString> e) throws Exception
                        {
                            String price = String.valueOf(App.mConfig != null ? App.mConfig.getUrgentChatPrice() / 100 : 0);
                            String descript = getString(R.string.tv_urgent_descript_1).replace("Price", price);
                            SpannableString span = new SpannableString(descript);
                            ForegroundColorSpan title = new ForegroundColorSpan(getResources().getColor(R.color.textTitle));
                            span.setSpan(title, 0, descript.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                            ForegroundColorSpan color = new ForegroundColorSpan(getResources().getColor(R.color.price));
                            span.setSpan(color, 2, 3 + price.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            e.onNext(span);
                            e.onComplete();
                        }
                    }).compose(RxUtils.<SpannableString>rxObservableSchedlers())
                            .compose(mActivity.<SpannableString>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Consumer<SpannableString>()
                            {
                                @Override
                                public void accept(SpannableString span) throws Exception
                                {
                                    view.setText(span);
                                }
                            });
                }
            }


            //异步设置联系方式UI样式
            private void setContactUi(final TextView view)
            {
                if (view != null)
                {
                    Observable.create(new ObservableOnSubscribe<SpannableString>()
                    {
                        @Override
                        public void subscribe(ObservableEmitter<SpannableString> e) throws Exception
                        {
                            String contact = getString(R.string.tv_contact);
                            SpannableString span = new SpannableString(contact);
                            ForegroundColorSpan text = new ForegroundColorSpan(getResources().getColor(R.color.textTitle));
                            span.setSpan(text, 0, contact.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                            ForegroundColorSpan red = new ForegroundColorSpan(getResources().getColor(R.color.price));
                            span.setSpan(red, contact.length() - 2, contact.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                            e.onNext(span);
                            e.onComplete();
                        }
                    }).compose(RxUtils.<SpannableString>rxObservableSchedlers())
                            .compose(mActivity.<SpannableString>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Consumer<SpannableString>()
                            {
                                @Override
                                public void accept(SpannableString span) throws Exception
                                {
                                    view.setText(span);
                                }
                            });
                }
            }
        };
        mAdapter.addAdapter(mPayAdapter);
        mPayAdapter.setData("");
    }

    @Override
    protected void initData()
    {
        super.initData();
        mPresenter.getLawyerSkill();
    }

    @Override
    public void showData(Object o)
    {
        super.showData(o);
        if (o instanceof List)
        {
            List<FieldBean> list = (List<FieldBean>) o;
            mTypeAdapter.setData(list);
        }
    }

    @OnClick({R.id.img_wen, R.id.tv_kefu, R.id.tv_action})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.img_wen:
                // TODO 咨询提示
                WebDataBean data = new WebDataBean();
                data.setTitle(getString(R.string.tv_consulting_prompt));
                data.setUrl("http://www.baidu.com");
                openActivity(WebViewActivity.class, data);
                break;
            case R.id.tv_kefu:
                //TODO 联系客服
                break;
            case R.id.tv_action:
                if (mPhone == null || TextUtils.isEmpty(mPhone.getText().toString())
                        || (!StringUtils.isMobile(mPhone.getText().toString())))
                {
                    alert(getString(R.string.alert_enter_phone));
                } else
                {
                    alert(getString(R.string.alert_send_phone_order_success));
                    doFinish(200);
                }
                break;
        }
    }
}
